﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI;
using SmartFramework.Core.Pages;

namespace SmartFramework.Core.Plugin.Pages {
	public class SmartPageFactory : PageHandlerFactory {
		static Regex mClassRegex;

		static void InitUrlRegex(HttpContext context) {
			mClassRegex = LazyInitializer.EnsureInitialized(
				ref mClassRegex,
				() =>
				{
					var appPath = HttpContext.Current.Request.ApplicationPath;
					if (!appPath.EndsWith("/")) {
						appPath += "/";
					}
					return new Regex(appPath + @"(.+?)\.aspx", RegexOptions.Compiled | RegexOptions.IgnoreCase);
				});
		}


		public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
		{
			InitUrlRegex(context);
			Type type = GetPageType(virtualPath);
			if(type!=null)
			{
				return (Page)Activator.CreateInstance(type);
			}
			return base.GetHandler(context,requestType,virtualPath,path);
		}

		private static Type GetPageType(string virtualPath)
		{
			string vp = virtualPath.Replace(".aspx", "").Replace("/", ".");
			foreach (var ns in SFSettings.GetNameSpaces()) {
				string[] typeInfo = ns.Split(',');
				var type = Type.GetType(typeInfo[0] + vp + "," + typeInfo[1]);
				if (type != null)
				{
					return type;
				}
			}
			return null;
		}
	}
}
